<template>
  <div class="app-login">
    <el-card shadow="always">
      <template #header>
        <span>登陆后进入系统</span>
      </template>
      <el-form ref="loginForm" :model="form" label-width="70px" :rules="rules">
        <el-form-item label="用户名" prop="adminname">
          <el-input v-model="form.adminname" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handlerLogin">登录</el-button>
          <el-button @click="handlerReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import AuthApiService from "@/api/auth";
import { mapActions } from "vuex";
export default {
  name: "AppLogin",
  data() {
    return {
      form: {
        adminname: "",
        password: "",
      },
      rules: {
        adminname: [
          {
            required: true,
            message: "请输入管理员用户名",
            trigger: "blur",
          },
          {
            min: 3,
            max: 5,
            message: "长度在 3 到 5 个字符",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            min: 3,
            max: 7,
            message: "长度在 3 到 7 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    ...mapActions("auth", ["LoginAction"]),
    handlerReset() {
      Object.keys(this.form).forEach((key) => {
        this.form[key] = "";
      });
    },
    handlerLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        // 自定义插件的方法
        // if (valid) {
        //   this.$confirm("哈哈哈", {
        //     title: "1213",
        //   }).then(() => {
        //     console.log(this.form, "-----");
        //   });
        // } else {
        //   this.$message.error("请输入正确的用户名和密码");
        // }

        // 方法一:
        // if (valid)
        //   this.$store.dispatch({
        //     // type需要添加命名空间,因为auth.js中添加了namespaced
        //     type: "auth/LoginAction",
        //     params: this.form,
        //   });

        // 方法二:
        if (valid) {
          const res = await this.LoginAction({ params: this.form });
          res && this.$router.push({ name: "statistic" });
        }
      });
    },
  },
};
</script>

<style lang="scss">
.app-login {
  background-color: var(--el-color-primary-light-5);
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  .el-card {
    width: 400px;
  }
}
</style>
